package top.lbqaq.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "Servlet3", value = "/Servlet3")
public class Servlet3 extends HttpServlet {
    private static final String[] USER_NAME = {"a", "b", "c"};
    private static final String[] PASSWORD = {"1", "2", "3"};

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || password == null || "".equals(username) || "".equals(password)) {
            req.setAttribute("msg", "用户名或密码不能为空！");
            req.getRequestDispatcher("/3.jsp").forward(req, resp);
            return;
        }
        HttpSession mySession = req.getSession();
        int errTime = (int) (mySession.getAttribute("errTime") == null ? 0 : mySession.getAttribute("errTime"));
        Date dbDate = (Date) mySession.getAttribute("dbDate");
        Date nowDate = new Date();
        if (errTime >= 3) {
            if (dbDate.after(nowDate)) {
                req.setAttribute("msg", "您被禁止登录！");
                req.getRequestDispatcher("/3.jsp").forward(req, resp);
                return;
            } else {
                errTime = 0;
            }
        }
        int i;
        for (i = 0; i < USER_NAME.length; i++) {
            if (username.equals(USER_NAME[i]) && password.equals(PASSWORD[i])) {
                errTime = 0;
                req.setAttribute("msg", "登陆成功！");
                break;
            }
        }
        if (i >= USER_NAME.length) {
            errTime += 1;
            if (errTime >= 3) {
                //单位为毫秒
                nowDate.setTime(nowDate.getTime() + 1 * 60 * 1000);
            }
            req.setAttribute("msg", "用户名或密码错误！");

        }
        mySession.setAttribute("errTime", errTime);
        mySession.setAttribute("dbDate", nowDate);
        req.getRequestDispatcher("/3.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
